/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.user;

import dao.UsersDAO;
import entity.Users;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Turtle
 */
public class register extends HttpServlet {

    private boolean checkEmail(String s) {
        if (s.equals("")) {
            return false;
        }
        if (s.indexOf(" ") > 0) {
            return false;
        }
        if (s.indexOf("@") == -1) {
            return false;
        }
        if (s.indexOf(".") == -1) {
            return false;
        }
        if (s.indexOf("..") != -1) {
            return false;
        }
        if (s.indexOf("@") != s.lastIndexOf("@")) {
            return false;
        }
        if (s.lastIndexOf(".") == s.length() - 1) {
            return false;
        }

        String str = "abcdefghikjlmnopqrstuvwxyz-@._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        for (int j = 0; j < s.length(); j++) {
            if (str.indexOf(s.charAt(j)) == -1) {
                return false;
            }
        }

        return true;
    }

    private boolean checkUserName(String s) {
        if (s.equals("")) {
            return false;
        }
        if (s.indexOf(" ") >= 0) {
            return false;
        }

        String str = "abcdefghikjlmnopqrstuvwxyz-._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        for (int j = 0; j < s.length(); j++) {
            if (str.indexOf(s.charAt(j)) == -1) {
                return false;
            }
        }

        return true;
    }

    private boolean checkPassword(String s) {
        if (s.equals("")) {
            return false;
        }
        if (s.trim().equals("")) {
            return false;
        }

        return true;
    }

    private boolean checkPassword2(String mk1, String mk2) {
        if (mk1.equals(mk2)) {
            return true;
        }

        return false;
    }
    
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet register</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet register at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        String url = "";

        if (action == null) {
            url = "userpages/register.jsp";
        } else if (action.equals("load")) {
            url = "userpages/register.jsp";
        }

        RequestDispatcher rd = request.getRequestDispatcher(url);
        rd.forward(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String action = request.getParameter("action");
        String url = "";

        session.setAttribute("ss_re_email", request.getParameter("register_email"));
        session.setAttribute("ss_re_name", request.getParameter("register_name"));

        String error_info = "";
        
        if (action == null) {
            url = "userpages/register.jsp";
        } else if (action.equals("register")) {
            if (request.getParameter("register_email") != null) {
                if (!checkEmail(request.getParameter("register_email"))) {
                    error_info = "Email is not valid";
                    request.setAttribute("error_info", error_info);
                    url = "userpages/register.jsp";
                } else if (UsersDAO.checkExistedEmail(request.getParameter("register_email"))) {
                    error_info = "Email has been existed";
                    request.setAttribute("error_info", error_info);
                    url = "userpages/register.jsp";
                } else if (!checkUserName(request.getParameter("register_name"))) {
                    error_info = "Username is not valid";
                    request.setAttribute("error_info", error_info);
                    url = "userpages/register.jsp";
                } else if (UsersDAO.checkExistedUsername(request.getParameter("register_name"))) {
                    error_info = "Username has been existed";
                    request.setAttribute("error_info", error_info);
                    url = "userpages/register.jsp";
                } else if (!checkPassword(request.getParameter("register_password"))) {
                    error_info = "Password is not valid";
                    request.setAttribute("error_info", error_info);
                    url = "userpages/register.jsp";
                } else if (!checkPassword2(request.getParameter("register_password"), request.getParameter("register_repassword"))) {
                    error_info = "Confirm-password is not right";
                    request.setAttribute("error_info", error_info);
                    url = "userpages/register.jsp";
                } else {
                    if (request.getParameter("recaptcha_challenge_field") != null && request.getParameter("recaptcha_response_field") != null) {
                        String remoteAddr = request.getRemoteAddr();
                        net.tanesha.recaptcha.ReCaptchaImpl reCaptcha = new net.tanesha.recaptcha.ReCaptchaImpl();
                        reCaptcha.setPrivateKey("6LcUpMgSAAAAADvB3WhgJac8hmj1hVk7rvSY-72F");

                        String challenge = request.getParameter("recaptcha_challenge_field");
                        String uresponse = request.getParameter("recaptcha_response_field");
                        net.tanesha.recaptcha.ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

                        if (reCaptchaResponse.isValid()) {
                            Users user = new Users();

                            user.setEmail(request.getParameter("register_email"));
                            user.setUsername(request.getParameter("register_name"));
                            user.setPassword(request.getParameter("register_password"));
                            //user.setType("normal");

                            if (UsersDAO.insertUsers(user)) {
                                session.setAttribute("user", "normal");
                                session.setAttribute("user_name", user.getUsername());

                                out.println("<script>alert('Đăng ký thành công')</script>");
                                out.println("<script>window.location='home?action=load'</script>");
                            } else {
                                out.println("<script>alert('Đăng ký thất bại')</script>");
                                out.println("<script>window.location='register?action=load'</script>");
                            }
                        } else {
                            error_info = "The confirm-string is not right";
                            request.setAttribute("error_info", error_info);
                            url = "userpages/register.jsp";
                        }
                    }
                }
            }
        }
        
        RequestDispatcher rd = request.getRequestDispatcher(url);
        rd.forward(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
